﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.UserModel;

namespace Office.Automatic.Library.Data.Utils.Excel
{
    internal static class ImportHelper
    {
        internal static object? ReadCellValue(this ICell cell, DataConverter converter, Type targetType,
            string? annotation)
        {
            var cellType = cell.CellType == CellType.Formula ? cell.CachedFormulaResultType : cell.CellType;

            switch (cellType)
            {
                case CellType.String:
                    return converter.ConvertTo(cell.StringCellValue, targetType, CellDataType.String, annotation);
                case CellType.Boolean:
                    return converter.ConvertTo(cell.BooleanCellValue, targetType, CellDataType.Boolean, annotation);
                case CellType.Numeric:
                    return converter.ConvertTo(cell.NumericCellValue, targetType, CellDataType.Numeric, annotation);
                case CellType.Blank:
                    return null;
                default:
                    throw new ArgumentException("Cell type not supported.", nameof(cell));
            }
        }

        internal static TValue? ReadCellValue<TValue>(this ICell cell, DataConverter converter, 
            string? annotation) 
        {
            var result = ReadCellValue(cell, converter, typeof(TValue), annotation);

            if (result == null) 
                return default;
            else
                return (TValue)result;
        }
    }
}
